package org.ratingviewer.ui.action;

import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.beans.PropertyVetoException;

import javax.swing.*;
import javax.swing.JInternalFrame.JDesktopIcon;

public class ActionShowInternalFrame extends AbstractResourcedAction {

	private static final long serialVersionUID = 1L;

	private final String frameTitle;

	private final JDesktopPane desktopPane;

	public ActionShowInternalFrame(String actionItem, String frameTitle, JDesktopPane desktopPane,
			JComponent shortcutHandler) {
		super(actionItem, shortcutHandler);

		if (desktopPane == null)
			throw new IllegalArgumentException("DesktopPane can't be null.");
		this.desktopPane = desktopPane;

		this.frameTitle = frameTitle;
	}

	public ActionShowInternalFrame(String actionItem, String frameTitle, JDesktopPane desktopPane) {
		this(actionItem, frameTitle, desktopPane, null);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if (frameTitle != null) {
			JInternalFrame foundFrame = null;
			JInternalFrame[] allFrames = desktopPane.getAllFrames();
			for (int i = 0; i < allFrames.length && foundFrame == null; i++) {
				if (frameTitle.equals(allFrames[i].getTitle()))
					foundFrame = allFrames[i];
			}

			if (foundFrame != null) {
				Rectangle frameBounds = null;
				JDesktopIcon desktopIcon = foundFrame.getDesktopIcon();
				if (desktopIcon.isShowing())
					frameBounds = foundFrame.getNormalBounds();
				else
					frameBounds = foundFrame.getBounds();

				desktopPane.scrollRectToVisible(frameBounds);

				try {
					foundFrame.setIcon(false);
					foundFrame.toFront();
					foundFrame.setSelected(true);
				} catch (PropertyVetoException ex) {
					// ignored
				}

			}
		}
	}
}
